package com.xianxian.user.util;

import com.xianxian.user.entity.Department;
import com.xianxian.user.model.dto.DepartmentTreeDTO;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 *
 * @author zhang
 */
public class TreeUtil {

    public static List<DepartmentTreeDTO> getDeptTree(List<Department> departmentList){
        List<DepartmentTreeDTO> treeList = new ArrayList<>();

        List<DepartmentTreeDTO> dtoList = new ArrayList<>();
        for (Department department : departmentList) {
            DepartmentTreeDTO dto = new DepartmentTreeDTO();
            BeanUtils.copyProperties(department,dto);
            dtoList.add(dto);
        }

        for (DepartmentTreeDTO node : dtoList) {
            if(node.getPId() == null){
                treeList.add(node);
            }

            for (DepartmentTreeDTO treeNode : dtoList) {
                if(node.getId().equals(treeNode.getPId())){
                    if(node.getChildren() == null){
                        node.setChildren(new ArrayList<>());
                    }
                    node.getChildren().add(treeNode);
                }
            }
        }

        return treeList;
    }


}
